//
//  FavoritesController.m
//  iMiniTao
//
//  Created by liunian on 13-8-19.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "FavoritesController.h"
#import "GMGridView.h"
#import "FavoritManager.h"
#import "FavoritCell.h"
#import "Favorit.h"
#import "GMGridView-Constants.h"
#import "GMGridViewCell+Extended.h"
#import "GMGridViewLayoutStrategies.h"
#import "ItemViewController.h"

#define kDefaultBottomBarHeight           44

@interface FavoritesController ()<FavoritManagerDelegate,GMGridViewDataSource,GMGridViewDelegate,GMGridViewSortingDelegate>
@property (nonatomic, retain) GMGridView    *gmGridView;
@property (nonatomic, assign) BOOL          isIphone5;
@property (nonatomic, assign) BOOL     isEditing;
@property (nonatomic, retain) UIButton      *editBtn;
@property (nonatomic, retain) UILabel       *theTitle;
@property (nonatomic, retain) UIImageView          *navImageView;
@property (nonatomic, retain) UIImageView          *bottomImageView;

@end

@implementation FavoritesController

- (void)dealloc{
    BMLog(@"dealloc");
    [[FavoritManager sharedManager] removeObserver:self];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.theTitle setText:@"我的收藏"];
    [self.view addSubview:self.navImageView];
    [self.view addSubview:self.bottomImageView];
    self.isIphone5 = self.view.frame.size.height > 480;
    [[FavoritManager sharedManager] addObserver:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[FavoritManager sharedManager] getFavorites];
    [MobClick beginLogPageView:@"收藏视图"];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"收藏视图"];
}
- (void)back{
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
    }];
}
- (void)editBtnClick{
    self.isEditing = !self.isEditing;
    
    if (self.isEditing) {
        [self.editBtn setBackgroundImage:IMGNAMED(@"btn_new_weibo_light.png") forState:UIControlStateNormal];
        [self.editBtn setBackgroundImage:IMGNAMED(@"btn_new_weibo.png") forState:UIControlStateHighlighted];
    }else{
        [self.editBtn setBackgroundImage:IMGNAMED(@"btn_new_weibo_light.png") forState:UIControlStateNormal];
        [self.editBtn setBackgroundImage:IMGNAMED(@"btn_new_weibo.png") forState:UIControlStateHighlighted];
    }
}

- (void)endEditState{
    self.isEditing = NO;
}

#pragma mark FavoritManagerDelegate
- (void)mkManagerFavoritesDidFinishedWithFavorites:(NSMutableArray *)favorites{
    [self.gmGridView reloadData];
}

#pragma mark GMGridViewDataSource
- (NSInteger)numberOfItemsInGMGridView:(GMGridView *)gridView{
    return [[FavoritManager sharedManager].favorites count];
}

- (CGSize)sizeForItemsInGMGridView:(GMGridView *)gridView
{
    return CGSizeMake(140.0f, 140.0f);
}

- (GMGridViewCell *)gmGridView:(GMGridView *)gridView cellForItemAtIndex:(NSInteger)index{
    CGSize size = [self sizeForItemsInGMGridView:gridView];
    FavoritCell *cell = (FavoritCell *)[gridView dequeueReusableCell];
    
    if (!cell) {
        cell = [[FavoritCell alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    }
    Favorit *obj = [[FavoritManager sharedManager].favorites objectAtIndex:index];
    [cell.contentImageView setImageWithURL:[NSURL URLWithString:obj.item.itemImageURLString]
                          placeholderImage:IMGNAMED(@"")
                                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
        
    }];

    return cell;
}

- (void)gmGridView:(GMGridView *)gridView deleteItemAtIndex:(NSInteger)index{
    
    if (index>=0 && index < [[FavoritManager sharedManager].favorites count]) {
        Favorit *obj = [[FavoritManager sharedManager].favorites objectAtIndex:index];
        [[FavoritManager sharedManager] removeItem:obj.item];
    }
}

#pragma mark - GMGridViewDelegate
- (void)gmGridViewDidEndEditing:(GMGridView *)gridView{
    self.isEditing = NO;
}

- (void)gmGridView:(GMGridView *)gridView pageNumberInGridView:(NSInteger)pageNumber{
}

- (void)gmGridView:(GMGridView *)gridView didSelectItemAtIndex:(NSInteger)index{

    if (self.gmGridView.isEditing) {
        [self endEditState];
        return;
    }
    Favorit *obj = [[FavoritManager sharedManager].favorites objectAtIndex:index];
    ItemViewController *itemVC = [[ItemViewController alloc] initWithMeItem:obj.item];
    [self.navigationController pushViewController:itemVC animated:YES];
}

#pragma mark - GMGridViewSortingDelegate
- (void)gmGridView:(GMGridView *)gridView didStartMovingCell:(GMGridViewCell *)cell{
    self.isEditing = YES;
    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         cell.deleteButton.alpha = 1.0;
                         cell.layer.transform = CATransform3DMakeScale(1.04, 1.04, 1.0);
                         cell.contentView.layer.shadowOpacity = 0.7;
                     }
                     completion:nil
     ];
}

- (void)gmGridView:(GMGridView *)gridView didEndMovingCell:(GMGridViewCell *)cell{
    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         cell.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.9);
                         cell.contentView.layer.shadowOpacity = 0;
                     }
                     completion:nil
     ];
}

- (void)gmGridView:(GMGridView *)gridView moveItemAtIndex:(NSInteger)oldIndex toIndex:(NSInteger)newIndex
{
    BMLog(@"[oldIndex:%d  , newIndex:%d]",oldIndex,newIndex);

    Favorit *obj1 = [[FavoritManager sharedManager].favorites objectAtIndex:oldIndex];

    [[FavoritManager sharedManager].favorites removeObject:obj1];
    [[FavoritManager sharedManager].favorites insertObject:obj1
                                                  atIndex:newIndex];
    [[FavoritManager sharedManager] reorderFavorites];
}
#pragma mark getter
- (UIImageView *)navImageView{
    if (!_navImageView) {
        CGFloat  h = [UIScreen mainScreen].bounds.size.height-20;
        _navImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame)-h, 320, kDefaultBottomBarHeight)];
        _navImageView.userInteractionEnabled = YES;
        _navImageView.backgroundColor = COLOR_RGB_NAV;
    }
    return _navImageView;
}

- (UILabel *)theTitle{
    if (!_theTitle) {
        _theTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 4, 300, 40)];
        _theTitle.backgroundColor = [UIColor clearColor];
        _theTitle.textAlignment = [Util getAlign:ALIGNTYPE_LEFT];
        _theTitle.font = FONT_TITLE(18.0f);
        [self.navImageView addSubview:_theTitle];
        _theTitle.textColor = [UIColor flatWhiteColor];
    }
    return _theTitle;
}
- (UIImageView *)bottomImageView{
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - kDefaultBottomBarHeight - _kSpaceHeight, 320, kDefaultBottomBarHeight)];
        _bottomImageView.backgroundColor = COLOR_RGB_BOTTOM;
        _bottomImageView.userInteractionEnabled = YES;
        [_bottomImageView setImage:IMGNAMED(@"bottomTabBarBackground.png")];
        
        UIImage *imgBack = IMGNAMED(@"btn_back.png");
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, floorf((_bottomImageView.bounds.size.height-imgBack.size.height)/2), imgBack.size.width, imgBack.size.height);
        [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:back];
        
        [back setBackgroundImage:IMGNAMED(@"btn_dis.png") forState:UIControlStateNormal];
        [back setBackgroundImage:IMGNAMED(@"btn_dis_light.png") forState:UIControlStateHighlighted];
    }
    return _bottomImageView;
}

- (UIButton *)editBtn{
    if (!_editBtn) {
        
        UIImage *imgTop = IMGNAMED(@"btn_new_weibo.png");
        _editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _editBtn.exclusiveTouch = YES;
        _editBtn.frame = CGRectMake(_bottomImageView.bounds.size.width-imgTop.size.width-10, floorf((_bottomImageView.bounds.size.height-imgTop.size.height)/2), imgTop.size.width, imgTop.size.height);
        [_editBtn addTarget:self action:@selector(editBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_editBtn setBackgroundImage:IMGNAMED(@"btn_new_weibo.png") forState:UIControlStateNormal];
        [_editBtn setBackgroundImage:IMGNAMED(@"btn_new_weibo_light.png") forState:UIControlStateHighlighted];
    }
    return _editBtn;
}
- (GMGridView *)gmGridView{
    if (!_gmGridView) {
        NSInteger spacing = 2;
        _gmGridView = [[GMGridView alloc] initWithFrame:CGRectMake(0,
                                                                   CGRectGetMaxY(self.navImageView.frame),
                                                                   320,
                                                                   self.view.bounds.size.height - kDefaultBottomBarHeight-self.navImageView.frame.origin.y-self.navImageView.bounds.size.height - _kSpaceHeight)];

        _gmGridView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _gmGridView.backgroundColor = [UIColor colorWithPatternImage:IMGNAMED(@"listCellBackground.png")];
        _gmGridView.itemHorizontalSpacing = self.isIphone5?10:10;
        _gmGridView.itemVerticalSpacing = self.isIphone5?6:10;
        
        _gmGridView.minEdgeInsets = UIEdgeInsetsMake(spacing, spacing, spacing, spacing);
        _gmGridView.centerGrid = YES;
        _gmGridView.actionDelegate = self;
        _gmGridView.sortingDelegate = self;
        _gmGridView.dataSource = self;
        _gmGridView.isDestop = NO;
        _gmGridView.layoutStrategy = [GMGridViewLayoutStrategyFactory strategyFromType:GMGridViewLayoutVertical];
        [self.view addSubview:_gmGridView];
    }
    return _gmGridView;
}

#pragma mark - setter methods
- (void)setIsEditing:(BOOL)isEditing{
    if (_isEditing != isEditing ) {
        
        _isEditing = isEditing;
        if (_isEditing) { //当为编辑状态时，flipper禁用
            [self.gmGridView setEditing:YES];
        } else { //恢复flipperalce
            [self.gmGridView setEditing:NO];
        }
    }
}
@end
